//
//  HRPlayView.swift
//  XMLA
//
//  Created by Gao on 17/2/17.
//  Copyright © 2017年 Odm. All rights reserved.
//

import UIKit
import SnapKit

protocol PlayViewDelegate: NSObjectProtocol {
    // 传入按钮的selected属性
    func playButtonDidClick(_ selected: Bool)
}

class HRPlayView: UIView {
    
    var circleIV: UIImageView!
    
    private var myContext = 0
    
    lazy var contentIV: UIImageView = {
        let imgView = UIImageView()
        
        // 绑定到圆视图
        self.circleIV.addSubview(imgView)
        
        imgView.snp.makeConstraints({(make) in
            make.edges.equalTo(UIEdgeInsetsMake(8, 8, 8, 8))
        })
        

        // KVO观察image变化, 变化了就初始化定时器, 值变化则执行task
        imgView.addObserver(self, forKeyPath: "image", options: .new, context: &self.myContext)
        
        // 作圆内容视图背景
        imgView.layer.cornerRadius = 22
        imgView.clipsToBounds = true
        
        return imgView
    }()
    
    // KVO观察image变化, 变化了就初始化定时器, 值变化则执行task
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if context == &self.myContext {
            // 启动定时器
            link.isPaused = false
            playButton.isSelected = true
            
        }else{
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    deinit {
        contentIV.removeObserver(self, forKeyPath: "image", context: &self.myContext)
    }

    // 懒加载playButton按钮
    lazy var playButton: UIButton = {
        
        let btn = UIButton(type: .custom)
        
        // 去掉长按高亮
        btn.isHighlighted = false
        
        // 被点击后 "avatar_bg" 透明
        btn.setBackgroundImage(UIImage(named: "avatar_bg"), for: .selected)
        btn.setImage(UIImage(named: "toolbar_pause_h_p"), for: .selected)
        
        self.addSubview(btn)
        
        btn.snp.makeConstraints({(make) in
            make.left.top.equalTo(2)
            make.right.equalTo(-2)
            make.bottom.equalTo(-7)
        })

        // 按钮点击后做的方法
        btn.addTarget(self, action: #selector(playButtonClick(_:)) , for: .touchUpInside)
        
        
        return btn
        
    }()


    func playButtonClick(_ sender: UIButton){
        
        guard let delegate = delegate else { return }
        
        // 点击图和不点击图交换
        sender.isSelected = !sender.isSelected
        link.isPaused = !sender.isSelected
        
        delegate.playButtonDidClick(sender.isSelected)
   }
    
    


    weak var delegate: PlayViewDelegate?
    
    // 设置一个私有的定时器
    fileprivate lazy var link: CADisplayLink = {
        // 创建定时器, 一秒钟调用rotation方法60次
        let myLink = CADisplayLink(target: self, selector: #selector(rotation))
        
        // 手动将定时器加入到事件循环中
        // commonModes会使得RunLoop会随着界面切换扔继续使用, 不然如果使用Default的话UI交互没问题, 但滑动TableView就会出现不转问题, 因为RunLoop模式改变会影响定时器调度
        myLink.add(to: .current, forMode: .commonModes)
        
        return myLink
        
    }()
    
    
    init() {
        super.init(frame: CGRect.zero)  //Fixme:这里有问题？？
        
        // 布局
        let backgoundIV = UIImageView(image: UIImage(named: "tabbar_np_normal"))
        addSubview(backgoundIV)
        backgoundIV.snp.makeConstraints({(make) in
            make.edges.equalTo(0)
        })
        circleIV = UIImageView(image: UIImage(named: "tabbar_np_loop"))
        backgoundIV.addSubview(circleIV)
        circleIV.snp.makeConstraints({(make) in
            make.left.top.equalTo(2)
            make.right.equalTo(-2)
            make.bottom.equalTo(-8)
        })
        // 设置circle的用户交互
        backgoundIV.isUserInteractionEnabled = true
        circleIV.isUserInteractionEnabled = true
        // 按钮被点击前
        playButton.setImage(UIImage(named: "tabbar_np_play"), for: .normal)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}

extension HRPlayView {
    /**  背景图rotation滚动 */
    func rotation() {
        circleIV.layer.transform = CATransform3DRotate(circleIV.layer.transform, CGFloat(angleToRadian(x: 72 / 60.0)), 0, 0, 1)
    }
    
    // MARK: - PlayButton,ContentIV,CADisplayLink定时器懒加载
    
    
    
    // 角度转弧度
    fileprivate func angleToRadian(x: Float) -> Float {
        return x / 180.0 * .pi
    }
    
}

